import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import load_iris
from sklearn.decomposition import PCA
from sklearn.preprocessing import StandardScaler

# 加载鸢尾花数据集
iris = load_iris()
X = iris.data
y = iris.target
feature_names = iris.feature_names
target_names = iris.target_names

# 标准化数据
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)

# 应用PCA降维
pca = PCA(n_components=2)
X_pca = pca.fit_transform(X_scaled)

# 查看主成分的解释方差比
print("各主成分的解释方差比:")
for i, ratio in enumerate(pca.explained_variance_ratio_):
    print(f"主成分 {i+1}: {ratio:.2%}")

print(f"总解释方差比: {sum(pca.explained_variance_ratio_):.2%}")

# 可视化降维结果
plt.figure(figsize=(12, 5))

# 原始数据的前两个特征
plt.subplot(1, 2, 1)
scatter = plt.scatter(X[:, 0], X[:, 1], c=y, cmap='viridis')
plt.xlabel(feature_names[0])
plt.ylabel(feature_names[1])
plt.title('原始数据（前两个特征）')
plt.colorbar(scatter)

# PCA降维结果
plt.subplot(1, 2, 2)
scatter = plt.scatter(X_pca[:, 0], X_pca[:, 1], c=y, cmap='viridis')
plt.xlabel('第一主成分')
plt.ylabel('第二主成分')
plt.title('PCA降维结果')
plt.colorbar(scatter)

plt.tight_layout()
plt.show()

# 查看主成分的组成
print("\n主成分组成:")
components = pca.components_
for i, component in enumerate(components):
    print(f"主成分 {i+1}:")
    for j, weight in enumerate(component):
        print(f"  {feature_names[j]}: {weight:.3f}")